//
//  SecondViewController.m
//  CustomNavigationTransition
//
//  Created by 朱志佳 on 2019/4/3.
//  Copyright © 2019 朱志佳. All rights reserved.
//

#import "SecondViewController.h"
#import "SLNavigationDelegate.h"

@interface SecondViewController ()

@property (nonatomic,strong) UIScreenEdgePanGestureRecognizer *edgePanGesture;
@property (nonatomic,strong) SLNavigationDelegate *navigationDelegate;

@end

@implementation SecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blueColor];
    [self initialize];
}

- (void)initialize {
    _edgePanGesture = [[UIScreenEdgePanGestureRecognizer alloc] initWithTarget:self action:@selector(handleEdgePanGesture:)];
    _edgePanGesture.edges = UIRectEdgeLeft;
    [self.view addGestureRecognizer:_edgePanGesture];
}

- (void)handleEdgePanGesture:(UIScreenEdgePanGestureRecognizer *)gesture {
    CGFloat translationX = [gesture translationInView:self.view].x;
    CGFloat translationBase = self.view.frame.size.width / 3;
    CGFloat translationAbs = ABS(translationX);
    NSLog(@"translationAbs:%f",translationAbs);
    CGFloat percent = translationAbs > translationBase ? 1.0 : translationAbs / translationBase;
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
        {
            _navigationDelegate = self.navigationController.delegate;
            _navigationDelegate.interactive = true;
            [self.navigationController popViewControllerAnimated:YES];
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            [_navigationDelegate.interactionController updateInteractiveTransition:percent];
        }
            break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateEnded:
        {
            if (percent > 0.5) {
                [_navigationDelegate.interactionController finishInteractiveTransition];
            }else {
                [_navigationDelegate.interactionController cancelInteractiveTransition];
            }
            _navigationDelegate.interactive = false;
        }
            break;
        default:
            break;
    }
}


- (IBAction)popAction:(id)sender {
    NSLog(@"self.navigationController.view:%@",self.navigationController.view);
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)dealloc {
    NSLog(@"%@ dealloc",NSStringFromClass(self.class));
}

@end
